package com.neusoft.news.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.neusoft.news.bean.User;
import com.neusoft.news.service.UserService;

/**
 * Servlet implementation class UserCreateServlet
 */
@WebServlet("/UserCreateServlet")
public class UserCreateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserCreateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		User user = new User();
		User user1 = new User();
		List<User>users = new ArrayList<User>();
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String sex = request.getParameter("sex");
		String brithday = request.getParameter("brithday");
		String tel = request.getParameter("tel");
		String address = request.getParameter("address");
		String level = request.getParameter("level");
		String loginid = request.getParameter("loginid");		
		
		user.setUserName(username);
		user.setUserPwd(password);
		user.setUserSex(sex);
		user.setUserBrithday(brithday);
		user.setUserTel(tel);
		user.setUserAddr(address);
		user.setUserLevel(level);
		user.setUserShinsa("1");	
		user1.setUserId(Integer.parseInt(loginid));
		
		UserService service = new UserService();
		try {
			if(service.insert(user) == true) {
				user1 = service.login(user1);
				users = service.selectOldUser();
				if(users!=null) {
					request.setAttribute("user", user1);
					request.setAttribute("users", users);
					request.getRequestDispatcher("users.jsp").forward(request, response);
				}else {
					request.getRequestDispatcher("error2.jsp").forward(request, response);
				}
			}else {
				request.getRequestDispatcher("error1.jsp").forward(request, response);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			request.getRequestDispatcher("error2.jsp").forward(request, response);
		}
	}

}
